package org.zjt.bean;

import com.sun.beans.editors.IntegerEditor;
import lombok.Data;
import org.apache.http.util.Asserts;

import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author juntao.zhang
 * @version V1.0
 * @Description: java 内省赋值操作
 * @Package org.zjt.bean
 * @date 2018/5/28 22:31
 */public class BeanMetaData {

    public static void main(String[] args) throws IntrospectionException {
        BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
        Arrays.stream(beanInfo.getPropertyDescriptors()).map(String::valueOf).forEach(System.out::println);

        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
        Arrays.stream(methodDescriptors).map(String::valueOf).forEach(System.out::println);

        beanInfo.getAdditionalBeanInfo();


        Optional<PropertyDescriptor> age = Arrays.stream(beanInfo.getPropertyDescriptors()).filter(item -> Objects.equals(item.getName(), "age")).findAny();
        Asserts.check(age.isPresent(),"age properties 不存在");

        PropertyDescriptor agePropertyDescriptor = age.get();


        Student student = new Student();
        agePropertyDescriptor.setPropertyEditorClass(IntegerEditor.class );
        PropertyEditor propertyEditor = agePropertyDescriptor.createPropertyEditor(student);
        propertyEditor.addPropertyChangeListener(evt ->{
            IntegerEditor integerEditor = (IntegerEditor)evt.getSource();
            Method writeMethod = agePropertyDescriptor.getWriteMethod();
            try {
                writeMethod.invoke(student,integerEditor.getValue());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });
        propertyEditor.setAsText("33");

        System.out.println(student.getAge());
    }
}


@Data
class Student{

    private Integer age;

}
